package com.ke.forum.forumapi.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ke.forum.common.common.Result;
import com.ke.forum.mbg.entity.Comment;
import com.ke.forum.mbg.dao.CommentMapper;
import com.ke.forum.forumapi.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ke.forum.mbg.entity.dto.CommentDto;
import com.ke.forum.mbg.entity.dto.UserDto;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 珂
 * @since 2021-05-22
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    CommentMapper commentMapper;

    @Override
    public Result addComment(Comment comment) {
        UserDto userDto = (UserDto) SecurityUtils.getSubject().getPrincipal();
        comment.setId(null);
        comment.setCreateTime(LocalDateTime.now());
        comment.setStatus(1);
        comment.setUserUuid(userDto.getUuid());
        comment.setChecked(0);
        commentMapper.insert(comment);
        return Result.SUCCESS(true);
    }

    @Override
    public Result listComment(Integer articleId, Integer current) {
        Page<CommentDto> page = new Page<>();
        page.setCurrent(current);
        page.setSize(10);
        Page<CommentDto> commentDtoPage = commentMapper.listComment(page, articleId);
        return Result.SUCCESS(commentDtoPage);
    }

    @Override
    public Result listReply(Integer commentId, Integer current) {
        Page<CommentDto> page = new Page<>();
        page.setCurrent(current);
        page.setSize(10);
        Page<CommentDto> commentDtoPage = commentMapper.listReply(page, commentId);
        return Result.SUCCESS(commentDtoPage);
    }

    @Override
    public Result deleteComment(Integer id) {
        UserDto userDto = (UserDto)SecurityUtils.getSubject().getPrincipal();
        Comment comment = commentMapper.selectById(id);
        if (!comment.getUserUuid().equals(userDto.getUuid())){
            return Result.FAIL("无法删除他人的评论");
        }
        commentMapper.deleteById(id);
        return Result.SUCCESS(true);
    }
}
